<template>
  <div class="cost-summary">
    <ProTable
      ref="reconciliation_letter_table"
      :immediate="false"
      :search-form="formList"
      :columns="columns"
      :request="getSettleLetters"
      :pagination="true"
      :before-search-submit="beforeSearchSubmit"
      :on-select-change="onSelectChange"
    >
      <template #extra>
        <Authc permissions="trade:settlement:report:ReconciliationLetter:edit">
          <Button type="primary" :disabled="generateAble" @click="generateSettleLetters">生成对账函</Button>
        </Authc>
        <Authc permissions="trade:settlement:report:ReconciliationLetter:edit">
          <Button type="primary" @click="deleteSettleLetters">删除</Button>
        </Authc>
      </template>
    </ProTable>
  </div>
</template>

<script>
import {omit} from 'lodash';
import ProTable from '@/components/ProTable';
import {getDateRangeDate} from '@/utils/date'
import {
  getOrderDictionary, getMerchantAllMerchant, getMerchantAllOrg, getSettleLetters,
  generateSettleLetters,deleteBySettleLettersCode,downLoadFile,isExistGenerateTask
} from '@/api/statement';
import util from '@/utils/util'
import {Modal} from "view-design";
import appService from '@/utils//appService';
import Authc from "@/components/Authc";
export default {
  components: {
    // Button,
    Authc,
    ProTable
  },
  data() {
    return {
      generateAble:true,
      selectList: [],
      formList: [
        {
          type: 'range',
          name: 'date',
          label: '统计周期',
          value: '',
          props: {
            placeholder: '请选择',
            format: 'yyyy年MM月dd日'
          }
        },
        {
          type: 'select',
          name: 'orderSource',
          label: '场景',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable: true
          }
        },
        {
          type: 'select',
          name: 'merchantCode',
          label: '商户名称',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable: true,
            filterable: true
          }
        },
        {
          type: 'select',
          name: 'org_code',
          label: '组织机构',
          value: '',
          props: {
            placeholder: '请选择',
            optionList: [],
            clearable: true,
            filterable: true
          }
        }
      ],
      columns: [
        {
          type: 'selection',
          width: 50,
        },
        {
          title: '序号',
          type: 'index',
          align: 'center'
        },
        {
          title: '统计周期',
          align: 'center',
          render: (h, params) => {
            return h('div', params.row.settle_start + "至" + params.row.settle_end);
          }
        },
        {
          title: '生成日期',
          key: 'createdDt',
          align: 'center'
        },
        {
          title: '文件名',
          key: 'settle_letters_file_name',
          align: 'center'
        },
        {
          title: '操作人',
          key: 'createdBy',
          align: 'center'
        },
        {
          title: '下载',
          key: 'download',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'a',
                {
                  on: {
                    click: () => this.downloadFile(params.row)
                  }
                },
                '下载'
              )
            ]);
          }
        }
      ]
    };
  },
  created() {
    this.initSearchValue()
    this.setGenerateTask()
  },
  methods: {
    getSettleLetters,
    async setGenerateTask(){
      const res=await isExistGenerateTask()
      console.log('setGenerateTask:',res)
      if (null != res && res.data.ret===0) {
        this.generateAble=res.data.data
      }
    },
    downloadFile(row) {
      console.log('downloadFile:',row)
      // appService.downloadFileFromFileSystem(row.settle_letters_file,row.settle_letters_file_name)
      // return
      if(row.settle_letters_file && row.settle_letters_file_name){
        appService.downloadFileFromFileSystem(row.settle_letters_file,row.settle_letters_file_name)
        // downLoadFile(row.settle_letters_file,row.settle_letters_file_name.replace(".zip",""))
      }
      // appService.downloadFileFromFileSystem(row.settle_letters_file,)
    },
    onSelectChange(rows) {
      if (rows && rows.length) {
        let selectList = []
        rows.map(item => {
          selectList.push(item.settle_letters_code)
        })
        this.selectList = selectList
      } else {
        this.selectList = []
      }
    },
    /**
     * 生成对账函
     */
    async generateSettleLetters() {
      let data = this.$refs['reconciliation_letter_table'].getSearchParams()
      const {date} = data
      if (!date || date[0] === '') {
        this.$Message.error('请选择查询条件~');
        return
      }
      this.generateAble=true
      Modal.confirm({
        title: "生成对账函提示",
        content: "生成对账耗时较久，请耐心等待，不要频繁点击生成对账函！",
        okText: "确定",
        onOk: async () => {

        }
      });
      const res = await generateSettleLetters(this.searchDateHandler(data))
      if (null != res && res.data.ret===0) {
        this.$Message.info("生成对账函成功！")
        this.refresh()
      } else {
        this.$Message.error(res.data.msg||"生成对账函失败！")
      }
      this.setGenerateTask()
    },
    refresh(){
      this.$refs['reconciliation_letter_table'].onSearch()
    },
    /**
     * 删除对账函
     */
    async deleteSettleLetters() {
      if (!this.selectList || this.selectList.length == 0) {
        this.$Message.error("请选择数据！")
        return
      }
      Modal.confirm({
        title: "确定删除",
        content: "删除后无法恢复",
        okText: "确定",
        cancelText: "取消",
        onOk: async () => {
          const res=await deleteBySettleLettersCode(this.selectList)
          this.$Message.info("删除成功！")
          this.refresh()
          this.selectList=[]
        }
      });

    },
    beforeSearchSubmit(data) {
      return omit(data, this.searchDateHandler(data))
    },
    searchDateHandler(data) {
      const {date} = data

      const [startDate, endDate] = getDateRangeDate(date)
      if (startDate) {
        data.settle_start = util.formatDate(startDate)
      }
      if (endDate) {
        data.settle_end = util.formatDate(endDate)
      }

      return data
    },
    async initSearchValue() {
      const orderSourceList = await getOrderDictionary("orderSource")
      const selectRevenueTypeList = orderSourceList.map(({value, key}) => {
        return {
          value: key,
          label: value
        };
      });
      this.setSearchOptionListInitValue("orderSource", selectRevenueTypeList)

      // 查询商户
      const merchantList = await getMerchantAllMerchant();
      const selectMerchantList = merchantList.map(({merchantCode, merchantName}) => {
        return {
          value: merchantCode,
          label: merchantName
        };
      });
      this.setSearchOptionListInitValue("merchantCode", selectMerchantList)

      // 查询机构
      const orgList = await getMerchantAllOrg();
      const selectOrgList = orgList.map(({organizationCode, organizationName}) => {
        return {
          value: organizationCode,
          label: organizationName
        };
      });
      this.setSearchOptionListInitValue("org_code", selectOrgList)
    },

    setSearchOptionListInitValue(name, value) {
      this.formList.map(item => {
        if (item.name === name && item.props) {
          item.props.optionList = value
        }
      })
    }
  }
};
</script>
